package com.leenmvc.core.web.controller;

import com.leenmvc.core.annotation.ApiDescription;
import com.leenmvc.core.annotation.Note;
import com.leenmvc.core.base.BaseController;
import com.leenmvc.core.dao.mysql.wrapper.QueryWrapper;
import com.leenmvc.core.security.User;
import com.leenmvc.core.security.entity.core.SysLogSql;
import com.leenmvc.core.security.entity.export.LogSqlExcel;
import com.leenmvc.core.security.service.core.SysLogSqlService;
import com.leenmvc.core.utils.ConvertUtils;
import com.leenmvc.core.utils.ExcelUtils;
import com.leenmvc.core.base.result.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@ApiDescription("SQL语句监控器")
@RequestMapping("system/sysLogSql")
public class SysLogSqlController extends BaseController<SysLogSql> {

    @Autowired
    SysLogSqlService sysLogSqlService;


    @DeleteMapping("deleteAll")
    @RequiresPermissions("system:sysLogSql:deleteAll")
    @Note("删除当前用户下的所有SQL日志信息")
    public Result deleteAll(){
        delete("username",User.getUsername());
        return new Result();
    }




    @GetMapping("export")
    @RequiresPermissions("system:sysLogSql:export")
    @Note("导出登录日志excel,若选中则导出选中,不选中导出全部")
    public void export(@RequestParam Map<String,Object> params, HttpServletResponse response) throws IOException {
        String fileName = String.valueOf(LocalDateTime.now());
        QueryWrapper wrapper = getQueryWrapper();
        wrapper.le("createDate",params.get("endTime"));
        wrapper.ge("createDate",params.get("startTime"));
        if(null != params.get("status") || !"".equals(params.get("status"))){
            wrapper.eq("status",params.get("status"));
        }
//        if(null != params.get("AL_creatorName") || !"".equals(params.get("AL_creatorName"))){
//            wrapper.eq("creatorName",params.get("AL_creatorName"));
//        }
        wrapper.eq("username",User.getUsername());
        List<Object> logs = sysLogSqlService.query(wrapper);
        List<LogSqlExcel> logSqlExcels = ConvertUtils.sourceToTarget(logs, LogSqlExcel.class);
        ExcelUtils.exportExcel(response, fileName, logSqlExcels, LogSqlExcel.class);
    }

}
